import { AlipayCircleOutlined, TaobaoCircleOutlined, WeiboCircleOutlined } from '@ant-design/icons';
import { Alert, Checkbox,message,Modal,Form,Input,notification } from 'antd';
import React, {useEffect, useState} from 'react';
import { Dispatch, AnyAction } from 'redux';
import { Link } from 'umi';
import { connect } from 'dva';
import { StateType } from '@/models/login';
import { LoginParamsType } from '@/services/login';
import { ConnectState } from '@/models/connect';
import LoginFrom from './components/Login';
import request from 'umi-request';
import router from 'umi/router';
import {setAuthority} from "@/utils/authority";
import styles from './style.less';
import { SmileOutlined } from '@ant-design/icons';

const { Tab, UserName, Password, Submit } = LoginFrom;
const FormItem = Form.Item;

interface LoginProps {
  dispatch: Dispatch<AnyAction>;
  userLogin: StateType;
  submitting?: boolean;
}

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);
const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};
const openNotificationWithIcon = () => {

  notification.open({
    message: '超级管理员账号密码',
    description:
      'super_admin 123456',
    icon: <SmileOutlined style={{ color: '#108ee9' }} />,
  });
  notification.open({
    message: '管理员账号密码',
    description:
      'admin 123456',
    icon: <SmileOutlined style={{ color: '#108ee9' }} />,
  });
  notification.open({
    message: '老师账号密码',
    description:
      'teacher 123456',
    icon: <SmileOutlined style={{ color: '#108ee9' }} />,
  });
  notification.open({
    message: '学生账号密码',
    description:
      'student 123456',
    icon: <SmileOutlined style={{ color: '#108ee9' }} />,
  });
};
const Login: React.FC<LoginProps> = props => {
  const { userLogin = {}, submitting } = props;
  const { status, type: loginType } = userLogin;
  const [autoLogin, setAutoLogin] = useState(true);
  const [type, setType] = useState<string>('account');
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  useEffect(() => {
    openNotificationWithIcon()
  }, []);
  const showModal = () => {
      setVisible(true)
  };

  const handleOk = async() => {
    const fieldsValue = await form.validateFields();
    console.log(fieldsValue);
    const hide = message.loading('正在发送邮件');

    request.post('/api/email', {
      data: {
        ...fieldsValue
      }
    }).then((response) => {
      console.log(response);
      if (response.code == 303) {
        message.error('账号或邮箱错误');
        hide();
      }
      if (response.code == 200) {
        message.success(response.msg);
        message.success('发送成功');
      }else{
        message.error('发送失败');
      }
    })
    setVisible(false)
  };

  const handleCancel = e => {
    console.log(e);
    setVisible(false)
  };

  const handleSubmit = (values: LoginParamsType) => {
    // const { dispatch } = props;
    // dispatch({
    //   type: 'login/login',
    //   payload: { ...values, type },
    // });
    console.log(values);
    if(values.password.length <= 5){
      message.error("密码不能小于6位数");
      return
    }
    // const { type } = this.state;

    request.post('/api/rest', {
      params : values
    }).then(function (response) {
      console.log(response);
      if(response.code == 303){
        message.error(`账号或密码错误`);
      }else{
        localStorage.setItem('antd_pro_id',response.data.id);
        localStorage.setItem('lession_token',response.data.token);
        localStorage.setItem('antd_pro_name',response.data.username);
        message.success(`登录成功`);
        console.log(response.data.permissions)
        let str :string = "";
        switch(response.data.permissions){
          case 1:
            str = "super_admin";
            break;
          case 2:
            str = "admin";
            break;
          case 3:
            str = "teacher";
            break;
          case 4:
            str = "student";
            break;
        }
        setAuthority(str);
        router.push('/welcome');
      }

    })

  };
  return (
    <div className={styles.main}>
      <LoginFrom activeKey={type} onTabChange={setType} onSubmit={handleSubmit}>
        <Tab key="account" tab="昵称登录">
          {status === 'error' &&
          loginType === 'account' &&
          !submitting &&
          this.renderMessage('账户或密码错误')}
          <UserName
            name="username"
            placeholder={`${'用户名'}`}
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              },
            ]}
          />
          <Password
            name="password"
            placeholder={`${'密码'}`}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />
        </Tab>
        <Tab key="student_number" tab="学号登录">
          {status === 'error' &&
          loginType === 'account' &&
          !submitting &&
          this.renderMessage('学号或密码错误')}
          <UserName
            name="student_number"
            placeholder={`${'学号'}`}
            rules={[
              {
                required: true,
                message: '请输入学号!',
              },
            ]}
          />
          <Password
            name="password"
            placeholder={`${'密码'}`}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />

        </Tab>
        <div>
          <Checkbox checked={autoLogin} onChange={e => setAutoLogin(e.target.checked)}>
            自动登录
          </Checkbox>
          <a
            style={{
              float: 'right',
            }}
            onClick={showModal}
          >
            忘记密码
          </a>
        </div>
        <Submit loading={submitting}>登录</Submit>
      </LoginFrom>
      <Modal
        title="通过邮箱找回密码"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}>
          <FormItem {...formLayout} label="请输入姓名"
                    name="username"
                    rules={[{ required: true, message: '请输入姓名！'}]}>
            <Input placeholder="请输入姓名"/>
          </FormItem>
          <FormItem {...formLayout} label="您的邮箱"
                    name="email"
                    rules={[{ required: true, message: '请输入邮箱！'}]}>
            <Input placeholder="请输入邮箱"/>
          </FormItem>
        </Form>
      </Modal>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
